package com.idanchuang.component.logback.converter;

import ch.qos.logback.classic.spi.ILoggingEvent;
import com.idanchuang.component.core.util.SpringUtil;
import org.apache.servicecomb.pack.omega.context.OmegaContext;

/**
 * @author Richard_yyf
 * @version 1.0 2021/7/5
 */
public class TxIdEnhancedTraceIdPatternConverter extends TraceIdPatternConverter {

    @Override
    public String convert(ILoggingEvent iLoggingEvent) {
        String traceId = super.convert(iLoggingEvent);
        try {
            OmegaContext omegaContext = SpringUtil.getBean(OmegaContext.class);
            if (omegaContext.globalTxId() == null) {
                return traceId;
            }
            // omega trace id
            return traceId
                    + "dtx:"
                    + omegaContext.globalTxId()
                    + ":"
                    + (omegaContext.localTxId() == null ? "" : omegaContext.localTxId())
                    + ";";
        } catch (Exception e) {
            return traceId;
        }
    }
}
